<template>
  <nut-form ref="formRef" :model="localForm" :disabled="!props.showButtons" class="max-w-[700rpx] w-full mx-auto box-border pgs">
    <template v-for="(cfg, key) in fieldConfig" :key="key">
      <template v-if="cfg.show && cfg.edit !== false">
        <nut-form-item :label="cfg.label" class="flex mb-[24rpx] items-start">
          <template #label>
            <view class="w-[132rpx] pt-[10rpx] text-[30rpx] text-gray-700">
              {{ cfg.label }}
              <text v-if="cfg.required" class="text-red-500 ml-[4rpx]">*</text>
            </view>
          </template>
          <template v-if="cfg.type === 'textarea'">
            <nut-textarea
              v-model="localForm[key]"
              :placeholder="cfg.placeholder || '请输入' + cfg.label"
              class="flex-1 px-[24rpx] py-[20rpx] rounded-[12rpx] bg-gray-50 border border-gray-200 focus:border-blue-500 text-[30rpx] box-border min-h-[240rpx]"
              autosize
              :readonly="cfg.readonly"
              rows="3"
              style="resize: none"
            />
          </template>
          <template v-else-if="cfg.type === 'boolean'">
            <nut-switch v-model="localForm[key]" :readonly="cfg.readonly" activeColor="#2196F3" inactiveColor="#e5e7eb" class="scale-125 ml-[8rpx] mt-[10rpx]" />
          </template>
          <template v-else-if="cfg.type === 'picker'">
            <view class="flex-1">
              <PickerInput
                :modelValue="localForm[key]"
                @update:modelValue="(value) => localForm[key] = value"
                :columns="cfg.options ? [cfg.options] : []"
                :placeholder="cfg.placeholder || '请选择' + cfg.label"
                :title="'请选择' + cfg.label"
                :dictCode="cfg.dictCode"
                :readonly="cfg.readonly"
              />
            </view>
          </template>
          <template v-else-if="cfg.type === 'radio'">
            <nut-radio-group v-model="localForm[key]" direction="horizontal">
              <nut-radio v-for="opt in getPickerOptions(key, cfg)" :key="getOptionValue(opt)" :label="getOptionValue(opt)" class="mr-[24rpx] text-blue-600">
                {{ getOptionText(opt) }}
              </nut-radio>
            </nut-radio-group>
          </template>
          <template v-else-if="cfg.type === 'checkbox'">
            <nut-checkbox-group v-model="localForm[key]" direction="horizontal">
              <nut-checkbox v-for="opt in getPickerOptions(key, cfg)" :key="getOptionValue(opt)" :label="getOptionValue(opt)" class="mr-[24rpx] text-blue-600">
                {{ getOptionText(opt) }}
              </nut-checkbox>
            </nut-checkbox-group>
          </template>
          <template v-else>
            <nut-input
              v-model="localForm[key]"
              :placeholder="cfg.placeholder || '请输入' + cfg.label"
              :type="cfg.type === 'number' ? 'number' : 'text'"
              :readonly="cfg.readonly"
              class="flex-1 px-[24rpx] py-[20rpx] bg-[#e0e0e0] rounded-[12rpx] bg-gray-50 border border-gray-200 focus:border-blue-500 text-[30rpx] box-border h-[80rpx]"
            />
          </template>
        </nut-form-item>
      </template>
    </template>
    <view class="mt-[48rpx] flex gap-[24rpx]" v-if="props.showButtons">
      <nut-button block type="default" class="h-[96rpx] rounded-[16rpx] text-[32rpx] font-bold shadow flex-1" @click="resetForm">取消</nut-button>
      <nut-button block type="primary" class="h-[96rpx] rounded-[16rpx] text-[32rpx] font-bold shadow flex-1 bg-blue-500 hover:bg-blue-600 active:bg-blue-700" @click="submitForm">保存</nut-button>
    </view>
  </nut-form>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from "vue";
import { cloneDeep } from 'lodash-es';
import { IconFont } from '@nutui/icons-vue-taro'
import { getDictWithCache } from '@/service/api/dict'
import PickerInput from './PickerInput.vue'
import Taro from "@tarojs/taro";

interface FieldConfig {
  show: boolean;
  label: string;
  edit?: boolean;
  type: string;
  required?: boolean;
  placeholder?: string;
  options?: Array<any>;
  dictCode?: string;
  readonly?: boolean;
}

const props = defineProps<{
  fieldConfig: Record<string, FieldConfig>;
  form: any;
  showButtons?: boolean;
}>();

// 确保多选框字段初始化为数组
const initCheckboxFields = (formData: any) => {
  const result = { ...formData };
  Object.keys(props.fieldConfig).forEach((key) => {
    const cfg = props.fieldConfig[key];
    if (cfg.type === 'checkbox') {
      if (Array.isArray(result[key])) {
        // 已经是数组，保持不变
        result[key] = result[key];
      } else if (typeof result[key] === 'string' && result[key]) {
        // 如果是字符串且不为空，按逗号分割转换为数组
        result[key] = result[key].split(',').map(item => item.trim());
      } else {
        // 其他情况初始化为空数组
        result[key] = [];
      }
    }
  });
  return result;
};

const localForm = ref(initCheckboxFields(cloneDeep(props.form)));
const emit = defineEmits<{
  (e: "submit", form: any, fieldConfig: any): void;
}>();

const formRef = ref();

// 获取选择器选项（仅用于非字典的选项）
const getPickerOptions = (key: string, cfg: FieldConfig) => {
  return cfg.options || [];
};

// 获取选项值
const getOptionValue = (opt: any) => {
  return typeof opt === 'object' ? opt.value : opt;
};

// 获取选项文本
const getOptionText = (opt: any) => {
  return typeof opt === 'object' ? opt.text : opt;
};

// 获取显示文本
const getDisplayText = (key: string, cfg: FieldConfig) => {
  if (!localForm.value[key]) return '';
  
  const options = getPickerOptions(key, cfg);
  const option = options.find((item: any) => {
    if (typeof item === 'object') {
      return item.value === localForm.value[key];
    }
    return item === localForm.value[key];
  });
  
  return option ? (option.text || option) : String(localForm.value[key]);
};

function resetForm() {
  // Object.keys(props.fieldConfig).forEach((key) => {
  //   if (props.fieldConfig[key].show) localForm.value[key] = "";
  // });
  Taro.navigateBack()
}

function submitForm() {
  // 表单验证
  const errors: string[] = [];
  
  Object.keys(props.fieldConfig).forEach((key) => {
    const cfg = props.fieldConfig[key];
    if (cfg.required && (!localForm.value[key] || localForm.value[key].toString().trim() === '')) {
      errors.push(`请${cfg.type === 'picker' ? '选择' : '输入'}${cfg.label}`);
    }
  });
  
  if (errors.length > 0) {
    // 这里可以使用 Taro.showToast 显示错误信息
    return;
  }
  
  // 处理提交数据，将多选框数组转换为逗号分隔的字符串
  const submitData = { ...localForm.value };
  Object.keys(props.fieldConfig).forEach((key) => {
    const cfg = props.fieldConfig[key];
    if (cfg.type === 'checkbox' && Array.isArray(submitData[key])) {
      submitData[key] = submitData[key].join(',');
    }
  });
  
  emit("submit", submitData, props.fieldConfig);
}



onMounted(() => {
  // 初始化表单数据
});

// 监听 props.form 的变化，确保多选框字段正确初始化
watch(() => props.form, (newForm) => {
  if (newForm) {
    localForm.value = initCheckboxFields(cloneDeep(newForm));
  }
}, { deep: true });
</script>

<style lang="scss">
.pgs {
  .nut-textarea {
    background-color: #f9fafb !important;
    padding: 4rpx 20rpx !important;
    border-radius: 12rpx !important;
  }

  .nut-input {
    background-color: #f9fafb !important;
    padding: 4rpx 20rpx !important;
    border-radius: 12rpx !important;
  }
}
</style>
